<template>
  <a-card>
    <a-spin :spinning="spinning" size="large">
      <div style="display: flex; height: 73vh">
        <Side :informationlist="informationlist"></Side>
        <div style="width: 80%; height: calc(100% - 40px); overflow-y: auto; margin-top: 16px" id="goods" ref="menu">
          <div id="matchingGood">
            <h1>搭配商品</h1>
            <a-divider dashed />
            <Commodity ref="commodity" @productChange="productChange"></Commodity>
          </div>

          <a-divider dashed />
          <div id="parameter">
            <h1>通用参数</h1>
            <Parameter ref="parameter" @parmeChange="parmeChange" :showFooter="showFooter" @shelfParameter="shelfParameter"></Parameter>
          </div>
          <a-divider dashed />
          <div id="currency">
            <h1>个性参数</h1>
            <div style="display: flex; margin-left: 70px; margin-bottom: 20px">
              <div style="flex: 0 0 auto;">选择渠道：</div>
              <a-checkbox-group v-model="type" @change="onChange">
                <a-checkbox value="B10-A01" name="type" disabled> BOX有搭搭配 </a-checkbox>
                <a-checkbox value="B10-A05" name="type" disabled> BOX企划搭配 </a-checkbox>
                <a-checkbox value="B10-A02" name="type" disabled> POS+零售搭配 </a-checkbox>
                <a-checkbox value="B10-A03" name="type" disabled> POS+导购素材 </a-checkbox>
                <a-checkbox value="B10-A04" disabled> 微商城商详单品搭配 </a-checkbox>
                <a-checkbox value="B10-A06" disabled> 微商城商详更多搭配 </a-checkbox>
                <a-checkbox value="B10-A07" disabled> 微商城内容社区搭配 </a-checkbox>
              </a-checkbox-group>
            </div>
            <!-- disabled -->
            <!-- 吸顶锚点导航 -->
            <div class="box_fixed" id="boxFixed" :class="isFixed ? 'is_fixed' : 'is_fixed'" v-if="ogMenuList.length > 0">
              <a-anchor :affix="false" :getContainer="gerGood" @click="anchorClick" :bounds="300">
                <a-anchor-link :href="item.herf" :title="item.title" class="handle-item" v-for="(item, index) in menuList" :key="index" />
              </a-anchor>
            </div>
            <template v-if="type.includes('B10-A01')">
              <div id="have" class="module">
                <Have ref="have"></Have>
              </div>
              <a-divider dashed />
            </template>
            <template v-if="type.includes('B10-A05')">
              <div id="plan" class="module">
                <Plan ref="plan" @getFromValue="getFromValue">
                  <!-- <template v-slot:formItem="{ form, labelCol, wrapperCol }">
                    <a-form-model ref="ruleForm" :label-col="labelCol" :wrapper-col="wrapperCol" :model="form" :rules="rules">
                      <a-form-model-item label="标题标题" prop="name">
                        <a-input v-model="form.name2" placeholder="请填写标题" style="width: 300px" :maxLength="20" />
                      </a-form-model-item>
                    </a-form-model>
                  </template>
                  <template v-slot:formFooter="{ form }">
                    <a-button type="primary" @click="getPlanForm(form)">
                      Primary
                    </a-button>
                  </template> -->
                </Plan>
              </div>
              <a-divider dashed />
            </template>

            <template v-if="type.includes('B10-A02')">
              <div id="retail" class="module">
                <Retail ref="retail" @retailChange="retailChange"></Retail>
              </div>
              <a-divider dashed />
            </template>
            <template v-if="type.includes('B10-A04')">
              <div id="curren" class="module">
                <Currency ref="currency"></Currency>
              </div>
              <a-divider dashed />
            </template>
            <template v-if="type.includes('B10-A06')">
              <div id="business" class="module">
                <Business ref="business"></Business>
              </div>
              <a-divider dashed />
            </template>
            <div id="munity" class="module" v-if="type.includes('B10-A07')">
              <Munity ref="munity"></Munity>
            </div>
            <div class="module" v-if="type.includes('B10-A03')">
              <Guide ref="guide"></Guide>
            </div>
          </div>
        </div>
      </div>
      <div class="footer-box" v-if="showFooter">
        <a-button @click="handleBack">取消</a-button>
        <a-button style="margin-left: 8px; margin-right: 24px" @click="newPresersave" type="primary">保存</a-button>
        <!-- <a-button style="margin-left: 8px; margin-right: 24px" @click="application" type="primary">保存并上架</a-button> -->
      </div>
      <div class="footer-box" v-else>
        <a-button style="margin-right: 24px" @click="handleBack">返回</a-button>
      </div>
    </a-spin>
  </a-card>
</template>
<script>
import { listByLook, createLook, updateLookPartFunction, upOrDown } from '@api/box/boxLook'
import Side from '@/views/box/components/Side/index'
import Have from './detailComponents/have'
import Plan from './detailComponents/planning'
import Commodity from './detailComponents/commodity'
import Parameter from './detailComponents/parameter'
import Retail from './detailComponents/retail'
import Munity from './detailComponents/munity'
import Currency from './detailComponents/currency'
import Business from './detailComponents/business.vue'
import Guide from './detailComponents/guide.vue'
import Header from '@/views/box/components/layouts/Header'
import { querySysCateTree } from '@api/box/api'
import { themeStatus } from '@/api/pos/match'
import { mixin } from './mixin'
import Vue from 'vue'
import { USER_INFO } from '@/store/mutation-types'

export default {
  mixins: [mixin],
  components: {
    Side,
    Commodity,
    Have,
    Plan,
    Parameter,
    Retail,
    Munity,
    Currency,
    Header,
    Business,
    Guide
  },
  data() {
    return {
      list: {}, //接收上下架参数
      spinning: false,
      type: [],
      isFixed: false,
      offsetTop: 0,
      offsetHeight: 0,
      productList: [],
      share: {},
      fashionerMatch: {},
      qihuaFashioner: {},
      userInfo: Vue.ls.get(USER_INFO),
      informationlist: [
        { title: '搭配商品', herf: '#matchingGood' },
        { title: '通用参数', herf: '#parameter' },
        { title: '个性参数', herf: '#currency' }
      ],
      ogMenuList: [
        { title: 'BOX有搭搭配', herf: '#have', code: 'B10-A01' },
        { title: 'BOX企划搭配', herf: '#plan', code: 'B10-A05' },
        { title: 'POS+零售搭配', herf: '#retail', code: 'B10-A02' },
        { title: 'POS+导购素材', herf: '#retail', code: 'B10-A03' },
        { title: '微商城商详单品搭配', herf: '#curren', code: 'B10-A04' },
        { title: '微商城商详更多搭配', herf: '#business', code: 'B10-A06' },
        { title: '微商城内容社区搭配', herf: '#munity', code: 'B10-A07' }
      ],
      menuList: [],
      retailInfo: {},
      form: {},
      rules: {},
      newLookId: '',
      hasNewLookId: false,
      lookId: '',
      showFooter: false,
      originType: '',
      retailId: '',
      matchId: '',
      planId: ''
    }
  },
  mounted() {
    // window.addEventListener('scroll', this.initHeight, true)
    // this.$nextTick(() => {
    //   this.offsetTop = document.querySelector('#boxFixed').offsetTop
    // })
  },
  activated() {
    this.spinning = false
    if (this.$route.params.id && this.$route.params.id != 'add') {
      this.lookId = this.$route.params.id
      this.getDetails()
    }
    this.showFooter = this.$route.params.handle == 'detail' ? false : true
  },
  deactivated() {
    this.type = []
    this.$refs.commodity.reset() // 商品清除
    this.$refs.parameter.reset() // 通用参数清除
  },
  destroyed() {
    // window.removeEventListener('scroll', this.handleScroll)
    // this.$destroy()
  },
  created() {
    this.getSysCateTree()
    this.getDetails()
    this.shelfParameter()
  },
  beforeRouteLeave(to, from, next) {
    this.$destroy()
    next()
  },
  methods: {
    shelfParameter(val) {
      console.log(val, 'aaaaaddd')
      this.list = val
    },
    // 保存并上架
    async application() {
      const params = {
        requestData: {
          id: this.$route.params.id,
          isPublish: this.list.isPublish,
          status: 1,
          otherChannelCanUse: this.list.otherChannelCanUse
        }
      }
      updateLookPartFunction(params).then(res => {
        if (res.code == 0) {
          this.$message.success('保存成功')
          // if (this.originType == 'B10-A02') {
          //   console.log('pos+零售搭配')
          //   this.retailType()
          // }
          // if (this.originType == 'B10-A01') {
          //   console.log('有搭搭配')
          //   this.matchType()
          // }
          // if (this.originType == 'B10-A05') {
          //   console.log('企划搭配')
          //   this.planType()
          // }

          this.$router.go(-1)
        } else {
          this.$message.warning(res.msg)
        }
      })
    },

    //仅保存
    async newPresersave() {
      const params = {
        requestData: {
          id: this.$route.params.id,
          isPublish: this.list.isPublish,
          status: this.list.status,
          otherChannelCanUse: this.list.otherChannelCanUse
        }
      }
      updateLookPartFunction(params).then(res => {
        if (res.code == 0) {
          this.$message.success('保存成功')
          if (this.originType == 'B10-A02') {
            console.log('pos+零售搭配')
            this.retailType()
          }
          if (this.originType == 'B10-A01') {
            console.log('有搭搭配')
            this.matchType()
          }
          if (this.originType == 'B10-A05') {
            console.log('企划搭配')
            this.planType()
          }

          this.$router.go(-1)
          // } else {
          //   this.$message.warning(res.msg)
        }
      })
    },
    retailType() {
      const data = {
        id: this.retailId,
        isShelf: this.list.status, // :1上架，0下架
        isDelete: false,
        realname: this.userInfo.realname,
        workNo: this.userInfo.workNo
      }
      themeStatus(data).then(res => {
        if (res.code == 200) {
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    planType() {
      const data = {
        requestData: {
          ids: [this.planId],
          type: this.list.status // :1上架，0下架
        }
      }
      upOrDown(data).then(res => {
        if (res.code == 0) {
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    matchType() {
      const data = {
        requestData: {
          ids: [this.matchId],
          type: this.list.status // :1上架，0下架
        }
      }
      upOrDown(data).then(res => {
        if (res.code == 0) {
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    getDetails() {
      this.spinning = true
      const data = {
        page: {
          pageNo: 1,
          pageSize: 10
        },
        requestData: {
          lookId: this.$route.params.id,
          type: 4
        }
      }

      listByLook(data).then(res => {
        console.log(res)
        this.spinning = false
        if (res.code === 0) {
          let data = res.data[0]

          this.originType = data.originSource

          this.$refs.commodity.setData(data.productList) // 商品回显
          this.$refs.parameter.setData(data) // 通用参数回显
          this.list = {
            isPublish: data.isPublish,
            status: data.status,
            otherChannelCanUse: data.otherChannelCanUse
          }
          // this.$refs.have.setData(data) // 有搭回显
          let lookList = data.sysLookTypes.map(item => item.type)
          this.menuList = []
          this.menuList = this.ogMenuList.filter(e => lookList.includes(e.code))
          this.type = lookList
          if (lookList.includes('B10-A01')) {
            this.$nextTick(() => {
              this.$refs.have.setData(data.bFashionerMatch) // 有搭
            })
            this.matchId = data.bFashionerMatch.id
          }
          if (lookList.includes('B10-A05')) {
            this.$nextTick(() => {
              this.$refs.plan.setData(data.qihuabFashionerMatch) // 企划
            })
            this.planId = data.qihuabFashionerMatch.id
          }
          if (lookList.includes('B10-A03')) {
            let value = {
              briefIntroduction: data.briefIntroduction,
              name: data.name
            }
            this.$nextTick(() => {
              this.$refs.guide.setData(value) // pos+导购素材
            })
          }
          if (lookList.includes('B10-A03')) {
            let value = {
              briefIntroduction: data.briefIntroduction,
              name: data.name
            }
            this.$nextTick(() => {
              this.$refs.guide.setData(value) // pos+导购素材
            })
          }
          if (lookList.includes('B10-A02')) {
            this.$nextTick(() => {
              let retail = {
                ...data.retail,
                publisherId: data.publisherId,
                publisherName: data.publisherName,
                name: data.name,
                briefIntroduction: data.briefIntroduction,
                isCreateBill: data.isCreateBill
              }
              this.$refs.retail.setData(retail) // 零售
              this.retailId = data.retail.outId
            })
          }
        }
      })
    },
    productChange(value) {
      this.productList = value
    },
    parmeChange(value) {
      console.log(value, 'value')
      this.share = value
    },
    retailChange(value) {
      this.retailInfo = value
    },
    anchorClick(e) {
      e.preventDefault()
    },
    getSysCateTree() {
      querySysCateTree('B10')
        .then(res => {
          const { code, result, message } = res
          if (code == 0) {
            let data = result
          } else {
            this.$message.error(message)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    gerGood() {
      return document.getElementById('goods')
    },
    conflicting() {
      return this.productList
    },

    initHeight() {
      // 设置或获取位于对象最顶端和窗口中可见内容的最顶端之间的距离 (被卷曲的高度)
      var scrollTop = this.$refs.menu.scrollTop || document.body.scrollTop
      // //如果被卷曲的高度大于吸顶元素到顶端位置 的距离
      this.isFixed = scrollTop > this.offsetTop + 475 ? true : false
    },
    // 业务渠道勾选
    onChange(checkedList) {
      this.menuList = this.ogMenuList.filter(e => checkedList.includes(e.code))
    },
    // 取消
    handleBack() {
      this.$refs.commodity.reset() // 商品清除
      this.$refs.parameter.reset() // 通用参数清除
      this.type = []
      this.$router.go(-1)
    },
    // 保存
    presersave() {
      let type = 0
      this.preservation(type)
    },
    // 保存并应用
    // application() {
    //   let type = 1
    //   this.preservation(type)
    // },
    async preservation(type) {
      this.spinning = true

      this.$refs.parameter.submitEvent() //
      if (!this.productList.length) {
        this.$message.error('请添加商品！')
        this.spinning = false
        return
      }
      if (!this.share) {
        this.$message.error('请正确填写内容！')
        this.spinning = false
        return
      }
      if (!this.type.length) {
        this.$message.error('请选择渠道！')
        this.spinning = false
        return
      }
      if (this.type.includes('B10-A01')) {
        let haveValidate = await this.$refs.have.validateForm() // 有搭
        if (!haveValidate) {
          this.$message.error('请正确填写有搭搭配内容！')
          this.spinning = false
          return
        }
      }
      if (this.type.includes('B10-A05')) {
        let planValidate = await this.$refs.plan.validateForm() // 企划
        if (!planValidate) {
          this.$message.error('请正确填写企划搭配内容！')
          this.spinning = false
          return
        }
      }
      if (this.type.includes('B10-A02')) {
        let retailValidate = await this.$refs.retail.validateForm() // 零售
        if (!retailValidate) {
          this.$message.error('请正确填写零售搭配内容！')
          this.spinning = false
          return
        }
      }

      let valueTypeMap = {
        // 有搭
        'B10-A01': {
          type: 'B10-A01',
          sonType: 'B10-A01-A01'
        },
        // 企划
        'B10-A05': {
          type: 'B10-A05',
          sonType: 'B10-A05-A01'
        },
        // post+ 零售
        'B10-A02': this.retailInfo,
        'B10-A04': {
          type: 'B10-A04',
          sonType: 'B10-A02-A02'
        },
        'B10-A06': {
          type: 'B10-A06',
          sonType: '	B10-A06-A01'
        },
        // 内容社区搭配
        'B10-A07': {
          type: 'B10-A07',
          sonType: 'B10-A07-A01'
        }
      }

      let sysLookType = this.type.map(k => valueTypeMap[k])
      let data = {
        type: type,
        sysLookType: sysLookType,
        productList: this.productList, // 商品
        share: this.share // 通用参数
      }

      await this.createOrUpdate(data) // 保存look
      await this.moduleSave(data, this.newLookId) // 保存业务渠道
      this.spinning = false
      this.$router.push('/box/operations/collocation/list')
    },
    async moduleSave(data, newLookId) {
      if (this.type.includes('B10-A01')) {
        await this.$refs.have.submitEvent(data, newLookId) // 有搭
      }
      if (this.type.includes('B10-A05')) {
        await this.$refs.plan.submitEvent(data, newLookId) // 企划
      }
      if (this.type.includes('B10-A02')) {
        await this.$refs.retail.submitEvent(data, newLookId) // pos+ 零售
      }

      if (this.type.includes('B10-A04')) {
        await this.$refs.currency.submitEvent(data, newLookId) // 微商城商详 单品搭配  https://testbzhz.jnbygroup.com/api/gateway/jic-backend-operation/operate/collocation/update
      }
      if (this.type.includes('B10-A06')) {
        await this.$refs.business.submitEvent(data, newLookId) // 微商城商详 更多搭配 https://testbzhz.jnbygroup.com/api/gateway/jic-backend-operation/operate/collocation/more/update
      }
      if (this.type.includes('B10-A07')) {
        await this.$refs.munity.submitEvent(data, newLookId) // 微商城内容 社区搭配
      }
      console.log('all done')
    },
    // 保存 look
    createOrUpdate(record) {
      const data = {
        requestData: {
          status: record.type,
          productList: record.productList.map(e => {
            return {
              productBrand: e.brand,
              productCode: e.name,
              productName: e.value,
              productColorName: e.color_name,
              productColor: e.colorno,
              productId: e.id,
              productImage: e.imgurl
            }
          }),
          lookDiagram: '',
          videoList:
            record.share.videoList && record.share.videoList.length > 0
              ? record.share.videoList.map(e => {
                  return {
                    type: 1,
                    url: e.url,
                    videoImg: e.url + '?vframe/jpg/offset/1'
                  }
                })
              : [],
          imgList:
            record.share.imgList && record.share.imgList.length > 0
              ? record.share.imgList.map(e => {
                  return {
                    type: 0,
                    url: e.url
                  }
                })
              : [],
          labelList: record.share.labelList,
          sysLookTypesList: record.sysLookType,
          whoUpdate: 1,
          gender: record.share.gender,

          level: record.share.level,
          originSource: record.share.originSource // 原始来源
        }
      }
      if (this.$route.params.id && this.$route.params.id != 'add') {
        data.requestData.id = this.$route.params.id
      }
      return createLook(data)
        .then(res => {
          if (res.code === 0) {
            console.log('looK接口', res.data)
            this.newLookId = res.data
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {})
    },
    getPlanForm(planForm) {
      // console.log(planForm, this.form) // 方式一
      this.$refs.plan.getFromValue() // 方式二
    },
    getFromValue(form) {
      console.log(form)
    }
  }
}
</script>
<style lang="less" scoped>
// #goods {
//   position: relative;
// }
.footer-box {
  font-size: 14px;
  font-weight: 500;
  box-shadow: 0 -1px 6px rgba(0, 0, 0, 0.1);
  position: relative;
  background-color: #fff;
  height: 60px;
  display: flex;
  // justify-content: flex-end;
  align-items: center;
  margin: 0 -24px -24px;
}
.box_fixed {
  width: calc(100% - 130px);
  height: 40px;
  // border-radius: 20px;
  margin: 0 auto;
  line-height: 40px;
  // background: #eeeeee;
  margin-left: 120px;
  margin-bottom: 40px;
}
.is_fixed {
  // position: fixed;
  position: sticky;
  position: -webkit-sticky;
  top: 0px;
  z-index: 9;
}
/deep/ .box_fixed .ant-anchor {
  display: flex;
  border-bottom: 1px solid #e8e8e8;
}
/deep/ .box_fixed .ant-anchor .ant-anchor-ink::before {
  background-color: transparent !important;
}
/deep/ .box_fixed .ant-anchor {
  padding-bottom: 15px !important;
  padding-right: 15px !important;
}
.footer-box {
  font-size: 14px;
  font-weight: 500;
  box-shadow: 0 -1px 6px rgba(0, 0, 0, 0.1);
  position: relative;
  background-color: #fff;
  height: 60px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.module {
  margin-left: 60px;
}
</style>

